package com.app.core.web.filter;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.app.core.common.AppCons;
import com.app.core.common.Result;
import com.app.core.common.ResultCode;
import com.app.core.session.UserSession;
import com.app.core.util.SysConfig;
import com.app.core.web.context.RequestContext;
import com.app.core.web.util.AppContextUtil;
import com.guda.mp.vo.SysResourceVo;

public class SecurityInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {
        UserSession userSession = RequestContext.getUserSession();
        if (userSession == null) {
            return true;
        }

        if (userSession.getLoginName().equals(SysConfig.get(AppCons.APP_SUPER_ACCOUNT))) {
            return true;
        }
        /*
         * 第1步. 先判断此URL是否需要鉴权
         */
//        Object meunUrlMapObj = AppContextUtil.getSessionValue(AppCons.SYS_MENU_URL_MAP_CACHE_KEY);
//        if (meunUrlMapObj == null) {
//            // 查询不到时，说明cache宕机或出现了其它问题，所以返回false
//            return false;
//        }

        // 获取请求url
        String contextPath = request.getContextPath();
        String requestURI = request.getRequestURI();
        requestURI = requestURI.substring(contextPath.length(), requestURI.length());
        requestURI = requestURI.split("\\?")[0];
        requestURI = requestURI.substring("/admin".length(), requestURI.length());

//        Map<String, SysResourceVo> urlMap = (Map<String, SysResourceVo>) meunUrlMapObj;
//        // 未纳入权限管理的url直接放行
//        if (!urlMap.containsKey(requestURI)) {
//            return true;
//        }

        /*
         * 第2步. 开始鉴权
         */
        Map<String, Integer> userHasMap = userSession.getUserPermissionUrl();
        // 有权限
        if (userHasMap != null && userHasMap.containsKey(requestURI)) {
            return true;
        }

        noPermission(request, response);

        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
        ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
        throws Exception {

    }

    public void noPermission(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
        String requestedWith = request.getHeader("x-requested-with");
        // ajax请求
        if (requestedWith != null && "XMLHttpRequest".equals(requestedWith)) {
            outJson(request, response, Result.error(ResultCode.ILLEGAL_ACCESS).toJson());
            return;
        } else {
            // 无权限
            response.sendRedirect(request.getContextPath() + "/admin/error/noPer");
            return;
        }
    }

    public void outJson(HttpServletRequest request, HttpServletResponse response, String msg) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setHeader("content-type", "application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.print(msg);
        out.flush();
    }

}
